﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParticleFactory
{

    #region Particle Resource
    public const string PREFIX = @"particles/";

    public static GameObject SpawnParticle(string resUrl)
    {
        string assetbundleName = PREFIX + resUrl;
        string assetName = CommonMethod.GetAssetNameFromAssetBundleName(assetbundleName);
        return GameObjectPoolManager.Instance.Spawn(assetbundleName, assetName);
    }

    public static void UnSpawnParticle(GameObject obj, float delay = 0f)
    {
        if (delay > 0)
        {
            GameObjectPoolManager.Instance.Unspawn(obj, delay);
        }
        else
        {
            GameObjectPoolManager.Instance.Unspawn(obj);
        }
    }

    public static void RegistParticle(string resUrl, LoadCompleteNotify callback)
    {
			string assetbundleName = PREFIX + resUrl;
			string assetName = CommonMethod.GetAssetNameFromAssetBundleName (assetbundleName);
			AssetLoad.AssetBundleManager.Instance.StartCoroutine (RegistParticle (assetbundleName, assetName, callback));
    }

    public static void UnRegistParticle(string resUrl)
    {
			string assetbundleName = PREFIX + resUrl;
			string assetName = CommonMethod.GetAssetNameFromAssetBundleName (assetbundleName);
			GameObjectPoolManager.Instance.UnRegist (assetbundleName, assetName);
			AssetLoad.AssetBundleManager.Instance.UnloadAssetBundle (assetbundleName);
    }

    private static IEnumerator RegistParticle(string assetbundleName, string assetName, LoadCompleteNotify callback)
    {
        AssetLoad.AssetBundleManager.Instance.LoadAssetBundle(assetbundleName);
        while (!AssetLoad.AssetBundleManager.Instance.IsLoadedAssetBundle(assetbundleName))
        {
            yield return null;
        }
        GameObjectPoolManager.Instance.Regist(assetbundleName, assetName);
        if (callback != null)
        {
            callback();
        }
    }

    #endregion

    #region ParticleObj
    public static ParticleObj CreateParticleObj(ParticleData pd)
    {
        GameObject obj = new GameObject("[" + pd.particleId + "]");
        var p = obj.AddComponent<ParticleObj>();
        p.Init(pd);
        return p;
    }


    #endregion

}
